import cv2
import numpy as np
import requests
import json
import re
from skimage.morphology import skeletonize
import matplotlib.pyplot as plt
from io import BytesIO
import base64
from PIL import Image
import math

class RadioWall:   
    def calculate_max_min(self, xy_bboxes):
        radio_wall = 1
        x_data = []
        y_data = []
        for i, bbox in enumerate(xy_bboxes):
            if bbox[0] == 0:
                index, x1, y1, x2, y2 = bbox
                index, x1, y1, x2, y2 = index, int(x1 * radio_wall), int(y1 * radio_wall), int(x2 * radio_wall), int(
                    y2 * radio_wall)
                new_box = index, x1, y1, x2, y2

                if x1 == x2:
                    x_data.append(new_box)
                elif y1 == y2:
                    y_data.append(new_box)
        x_max = 0
        x_min = 10000
        for line1 in y_data:
            if line1[3] >= x_max:
                x_max = line1[3]
            if line1[1] <= x_min:
                x_min = line1[1]

        y_max = 0
        y_min = 10000
        for line1 in x_data:
            if line1[4] >= y_max:
                y_max = line1[4]
            if line1[2] <= y_min:
                y_min = line1[2]

        return x_min, y_min, x_max, y_max

    def process_and_display(self, wall_contours,pointData):
        # 芒果除以贝壳长度倍数
        # a = 346px
        # b = 266px
        # c = (6189+6309)/2 = 6249mm
        # d = 630mm/2
        # (a/b)*(c+d)/a = (346px/266px)/(6249+315)mm/346px =  (346/266)/6564/346 =  24.6767 mm/px
        first_row_sum, last_row_sum, w, h, max_min  = pointData
        x_min, y_min, x_max, y_max = self.calculate_max_min(wall_contours)
        a = w
        b = x_max - x_min
        c = (first_row_sum + last_row_sum) / 2
        d = 630 / 2
        radio_wall = (a / b) * (c + d) / a
        width_height = (w, h)
        return radio_wall







